﻿using System;
using ch03.binary.module;

namespace ch03.binary.wasm_reader
{
    public partial struct WasmReader
    {
        // code sec
        private Code[] ReadCodeSec()
        {
            var vec = new Code[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = ReadCode(i);
            }

            return vec;
        }

        private Code ReadCode(int idx)
        {
            var n = ReadVarU32();
            var remainingBeforeRead = Remaining();
            var code = new Code
            {
                Locals = ReadLocalsVec(),
                Expr = ReadExpr(),
            };
            if (Remaining() + (int) n != remainingBeforeRead)
            {
                Panic.Run("invalid code[%d]", idx);
            }

            if (code.GetLocalCount() >= UInt32.MaxValue)
            {
                Panic.Run("too many locals: {0:D}", code.GetLocalCount());
            }

            return code;
        }

        private Locals[] ReadLocalsVec()
        {
            var vec = new Locals[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = ReadLocals();
            }

            return vec;
        }

        private Locals ReadLocals()
        {
            return new()
            {
                N = ReadVarU32(),
                Type = ReadValType(),
            };
        }
    }
}